package logic

import (
	"context"
	"zhihu/models/mysql"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProblemAListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProblemAListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProblemAListLogic {
	return &ProblemAListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProblemAListLogic) ProblemAList(in *zhihurpc.ProblemAListRequest) (*zhihurpc.ProblemAListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	var problemlist []mysql.Problem

	offset := (page - 1) * pageSize
	mysql.DB.Debug().Where("title like ?", "%"+in.Title+"%").Offset(int(offset)).Limit(int(pageSize)).Find(&problemlist)

	var problemLists []*zhihurpc.ProblemAList
	for _, problem := range problemlist {
		list := zhihurpc.ProblemAList{
			Title:        problem.Title,
			ProblemImage: problem.ProblemImage,
			Hot:          int64(problem.Hot),
			UserId:       int64(problem.UserId),
		}
		problemLists = append(problemLists, &list)
	}

	return &zhihurpc.ProblemAListResponse{
		List: problemLists,
	}, nil
}
